<?php
/**
 * 
 * 数据库操作类
 * @author ChunYang.Jiang<chunyang@staff.sina.com.cn>
 * @copyright sina
 *
 */
class Db
{
	public $_linkid = null;
	
	public static $_instance = NULL;
	
	public $_lastSql = '';
	
	public $_error = '';
	/**
	 * 
	 * 避免类被初始化
	 * @param unknown_type $type
	 */
	private function __construct($type='master')
	{
		if ($type=='master'){
			$db = Config::$DB['master'];
		}else{
			$db = Config::$DB['slave'];
		}
		$this->_linkid = mysql_connect("{$db['host']}:{$db['port']}", $db['user'], $db['pass']) or die('count connect to mysql server');
		mysql_select_db($db['name'], $this->_linkid) or die(mysql_error($this->_linkid));
	}
	/**
	 * 
	 * 单件模式
	 * @param unknown_type $type
	 */
	public static function getInstance($type='master')
	{
		if(!isset(self::$_instance[$type]) || !(self::$_instance[$type] instanceof self)){
			self::$_instance[$type] = new self($type);
		}
		return self::$_instance[$type];
	}
	
	/**
	 * 
	 * 取Slave服务器
	 */
	public static function db_read()
	{
		return self::getInstance('slave');
	}
	
	/**
	 * 
	 * 取master服务器
	 */
	public static function db_write()
	{
		return self::getInstance('master');
	}
	
	/**
	 * 
	 * 执行查询
	 * @param unknown_type $sql
	 */
	public function query($sql)
	{
		$this->_lastSql = $sql;//echo $sql . '<br>';
		$result = mysql_query($this->_lastSql, $this->_linkid);
		if($result){
			return $result;
		}else{
			$this->_error = mysql_error($this->_linkid);
			Util::log("QueryError:{$this->_error}:SQL:$this->_lastSql");
			return FALSE;
		}
	}
	
	public function getLastInsertId()
	{
		return mysql_insert_id($this->_linkid);
	}
	
	public function getAffectedRows()
	{
		return mysql_affected_rows($this->_linkid);
	}
	
	public function getLastSql()
	{
		return $this->_lastSql;
	}
	
	public function getError()
	{
		return mysql_error($this->_linkid);
	}
}